import qs from 'qs'
import frontMatter from 'front-matter';


export const { format: formatNumber } = Intl.NumberFormat('en-GB', {
  notation: 'compact',
  maximumFractionDigits: 1,
})
export const stringToUtf8Hex = function (str: string) {
  let utf8Hex = ''
  for (let i = 0; i < str.length; i++) {
    const code = str.charCodeAt(i)
    if (code < 128) {
      utf8Hex += code.toString(16).padStart(2, '0')
    }
    else if (code < 2048) {
      utf8Hex += (192 | (code >> 6)).toString(16).padStart(2, '0')
      utf8Hex += (128 | (code & 63)).toString(16).padStart(2, '0')
    }
    else {
      utf8Hex += (224 | (code >> 12)).toString(16).padStart(2, '0')
      utf8Hex += (128 | ((code >> 6) & 63)).toString(16).padStart(2, '0')
      utf8Hex += (128 | (code & 63)).toString(16).padStart(2, '0')
    }
  }
  return utf8Hex
}
// 图片转 base64
export function imageToBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

/**
 * 处理上报header中的地址，防止 header size 过大 报错431
 * @param href string访问地址
 * @returns {string} 访问地址
 */
export function cutParamsInUrl(href: string): string {
  if (!href)
    return ''
  try {
    const location = new URL(href)
    const query = qs.parse(location.search, { ignoreQueryPrefix: true })
    for (const k in query) {
      if (typeof query[k] === 'string') {
        query[k] = query[k]?.substring(0, 100)
      }
    }
    location.search = qs.stringify(query)
    return location.href
  }
  catch (error) {
    // eslint-disable-next-line no-console
    console.log(error)
    return href
  }
}

/**
 * 处理多选数据 1.空值 清空select 2.重复项取消 3.未选中的添加
 */
export function formatSelectedData(
  current: string | object | undefined | null,
  selectedList: any[],
  judge: (a: { [name: string]: unknown }, b: { [name: string]: unknown } | unknown) => boolean,
): object[] {
  if (!current)
    return []
  const index = selectedList.findIndex((item) => {
    if (typeof item === 'string') {
      return item === current
    }
    else {
      return judge && judge(item, current)
    }
  })
  if (index > -1) {
    selectedList.splice(index, 1)
  }
  else {
    selectedList.push(current)
  }
  return selectedList
}

// 去除顶部---之间数据
export const metaConverter = (readmeText: string) => {
  try {
    const text = readmeText.replace(/^[\s\S]*?---[\s\S]*?---/g, '');
    return text;
  } catch {
    return readmeText;
  }
};


export function loadScript(src: string, callback: any) {
  const script = document.createElement('script')
  script.type = 'text/javascript'
  script.src = src
  script.onload = callback
  document.head.appendChild(script)
}
